package com.yznote.compileserver.yCompile.process;


import sun.nio.cs.UTF_32;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class ProcessManage {
    // 进程的管理
    private Process process;
    public ProcessManage(Process p){
        this.process = p;
    }

    /**
     * 这是一个阻塞的方法 当进程未结束时 永远读不完 读取正确输入流
     * @return
     * @throws IOException
     */
    public String readAll() throws IOException {
        // 读取输入流里面所有数据
         InputStream inputStream = process.getInputStream();
         InputStreamReader in = new InputStreamReader(inputStream,"GBK");
         char[] resp = new char[1000];
         int len = 0;
         int ind = 0;
         while((len=in.read(resp,ind,resp.length-ind))!=-1) { // 这里有可能进行阻塞 当进程未结束时
             ind = ind + len;
         }
         return new String(resp,0,ind);
    }

    /**
     * 读取错误输入流
     * @return
     * @throws IOException
     */
    public String readError() throws IOException{
        InputStream errorStream = process.getErrorStream();
        InputStreamReader in = new InputStreamReader(errorStream, "GBK");
        char[] resp = new char[1000];
        int len = 0;
        int ind = 0;
        while((len=in.read(resp,ind,resp.length-ind))!=-1) { // 这里有可能进行阻塞 当进程未结束时
            ind = ind + len;
        }
        return new String(resp,0,ind);
    }
    /**
     * 判断进程是否存活
     * @return
     */
    public boolean isAlive(){
        return this.process.isAlive();
    }

    /**
     * 杀死进程
     */
    public void kill(){
        this.process.destroy();
    }

    /**
     * 等待进程结束
     * @param timeout
     * @param unit
     * @return
     * @throws Exception
     */
    public long trywait(long timeout, TimeUnit unit) throws Exception{
        long res = 0;
        while(process.isAlive()){
            Thread.sleep(1);
            res+=1;
            if(res>unit.toMillis(timeout)){
                throw new RuntimeException("进程超时");
            }
        }
        return res;
    }

    /**
     * 与进程进行交互
     * @param cmd
     */
    public void writeIntoPorcess(String cmd) throws IOException{
        OutputStream outputStream = process.getOutputStream();
        outputStream.write(cmd.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
    }
    /**
     o* 关闭所有流
     */
    public void closeAllStream() throws IOException{
        process.getOutputStream().close();
        process.getInputStream().close();
        process.getErrorStream().close();
    }
}
